package myoa

import myoa.tool.StringTool

class EmployeeController {
    // id = company.id
    def create(Long id) {
        if (id) {    // create from company page
            [company: Company.get(id)]    // <g:if test="${company}">
        }
    }

    def save() {
        Employee e = new Employee(params)
        e.traceCreate()
        e.save()

        if (params.createFromCompanyPage) {
            if (e.id) {
                flash.message = message(code: 'default.save.success')
                redirect(controller: 'company', action: 'show', id: e.company.id)
            } else {
                flash.message = message(code: 'default.save.failed')
                render(view: "create", model: [company: e.company, employee: e])   //<g:if test="${company}">
            }
        } else {
            if (e.id) {
                flash.message = message(code: 'default.save.success')
                redirect(action: 'show', id: e.id)
            } else {
                flash.message = message(code: 'default.save.failed')
                render(view: "create", model: [employee: e])
            }
        }
    }

    def show(Long id) {
        [employee: Employee.get(id)]
    }

    def edit(Long id) {
        [employee: Employee.get(id)]
    }

    def update(Long id) {
        Employee e = Employee.get(id)
        e.properties = params
        e.traceUpdate()

        if (e.save()) {
            flash.message = message(code: 'default.save.success')
            redirect(action: 'show', id: id)
        } else {
            flash.message = message(code: 'default.save.failed')
            render(view: "edit", model: [employee: e])
        }
    }

    def delete(Long id) {
        Employee e = Employee.get(id)
        e.delete()
        flash.message = message(code: 'default.delete.success', args: [e.name])
        redirect(action: 'list')
    }

    def list() {
        params.max = StringTool.paginateMax(params.max)
        [employees: Employee.findAll(params), total: Employee.count()]
    }
}
